package com.coldworks.base.task;

import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;

import com.coldworks.base.BaseThread;
import com.coldworks.base.manager.BasePrefManager;
import com.coldworks.base.util.BaseCONST;
import com.coldworks.coldjoke.R;

/**
 * 桌面图标生成器
 * 
 * @since 2012-03-23
 */
public class BaseShortcutSetupTask extends BaseThread {
	Context ctx;
	int versionCode;

	public BaseShortcutSetupTask(Context ctx, int versionCode) {
		this.ctx = ctx;
		this.versionCode = versionCode;
	}

	@Override
	public void run() {
		try {
			Thread.sleep(BaseCONST.TASK.SHORTCUT_SETUP_SECOND * 1000);
		} catch (InterruptedException e) {
			log.error("", e);
			return;
		}
		log.info("start");
		if (BasePrefManager.getInstance().getIntFromPrefs(ctx,
				BaseCONST.KEY.SETUP_SHORTCUT, 0) == versionCode) {
			log.info("nothing");
			return;
		}

		Intent oldMainIntent = new Intent(Intent.ACTION_MAIN);
		oldMainIntent.setClassName(ctx, ctx.getClass().getName());
		Intent delOldMainIntent = new Intent(
				BaseCONST.SHORTCUT.ACTION_DEL_SHORTCUT);
		delOldMainIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
				Intent.ShortcutIconResource.fromContext(ctx,
						R.drawable.ic_launcher));
		delOldMainIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, ctx
				.getResources().getString(R.string.app_name));
		delOldMainIntent.putExtra(BaseCONST.SHORTCUT.SHORTCUT_DUPLICATE, false);
		delOldMainIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, oldMainIntent);
		ctx.sendBroadcast(delOldMainIntent);
		log.info("old shortcut deleting");

		Intent newMainIntent = new Intent(Intent.ACTION_MAIN);
		newMainIntent.setClassName(ctx, ctx.getClass().getName());
		newMainIntent.setClass(ctx, ctx.getClass());
		newMainIntent.setAction("android.intent.action.MAIN");
		newMainIntent.addCategory("android.intent.category.LAUNCHER");
		Parcelable icon = Intent.ShortcutIconResource.fromContext(ctx,
				R.drawable.ic_launcher);
		Intent addNewMainIntent = new Intent(
				BaseCONST.SHORTCUT.ACTION_ADD_SHORTCUT);
		addNewMainIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
		addNewMainIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
				(String) ctx.getString(R.string.app_name));
		addNewMainIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, newMainIntent);
		addNewMainIntent.putExtra(BaseCONST.SHORTCUT.SHORTCUT_DUPLICATE, false);
		ctx.sendBroadcast(addNewMainIntent);
		BasePrefManager.getInstance().setIntToPrefs(ctx,
				BaseCONST.KEY.SETUP_SHORTCUT, versionCode);
		log.info("new shortcut creating");
	}
}
